<?php

class Default_Model_BookmarkManager
{

    public $Bookmarks; 
    public $Collated; 
    public $DataURI;

    function __construct($param="")
    {       
        Zend_Session::start();
        $this->Session = new Zend_Session_Namespace ('Params');
        $this->DataURI  = DATA_PATH . "/bookmarks.xml";
        if (file_exists($this->DataURI)) {
            $this->bookmarks = array();
            $xml = simplexml_load_file($this->DataURI);
            $query = strlen($param) == 0 ? "//bookmark" : "//bookmark[contains(Name, '{$param}')]";
            $bookmarks  = $xml->xpath($query); 
            foreach ($bookmarks as $bookmark) {
                $b = new Default_Model_Bookmark; 
                $b->Load ($bookmark); 
                $this->Bookmarks[] = $b; 
            } 
            return; 
        }
        $this->LoadBookmarks();
    }

    function Collate() 
    { 
        $this->Collated = array();
        foreach ($this->Bookmarks as $bookmark) {
            if (!is_array( $this->Collated [$bookmark->Group] )) $this->Collated [$bookmark->Group] = array();
            $this->Collated [$bookmark->Group][] = $bookmark;
        }
    }

    function Remove($groupname, $index) 
    {  
        $doc = new DOMDocument();
        $doc->load($this->DataURI); 
        $xpath = new DOMXpath($doc);
        foreach($xpath->query("//bookmark[Path='{$groupname}.{$index}.xml']") as $node) {
            $node->parentNode->removeChild($node);
        }
        $doc->save($this->DataURI); 
        $destfile   = DATA_PATH . "/bookmark/{$groupname}.{$index}.xml"; 
        if (file_exists($destfile)) unlink ($destfile);
    }

    function RemoveByPath($groupname, $path) 
    {  
        $doc = new DOMDocument();
        $doc->load($this->DataURI); 
        $xpath = new DOMXpath($doc);
        foreach($xpath->query("//bookmark[Path='{$path}']") as $node) {
            $node->parentNode->removeChild($node);
        }
        $doc->save($this->DataURI); 
        $destfile   = DATA_PATH . "/bookmark/{$path}"; 
        if (file_exists($destfile)) unlink ($destfile);
    }

    function Add($groupname, $index) 
    { 
        $DATA_URI   = DATA_PATH . "/index/{$groupname}.xml"; 
        $destName   = "{$groupname}.{$index}.xml";  
        $savedparam = $this->Session->Saved; 
        if (strlen($savedparam) > 0) {
            $DATA_URI = DATA_PATH . "/search/{$groupname}/{$savedparam}.xml"; 
            $destName = "{$groupname}.{$savedparam}.{$index}.xml"; 
        }

        $destfile = DATA_PATH . "/bookmark/{$destName}"; 

        if (file_exists($DATA_URI)) 
        {
            $xml = simplexml_load_file($DATA_URI);
            $result  = $xml->xpath("//list/article[@index='{$index}']/items/article"); 
		//    uasort($result, 'cmpx'); 
             $first = $result[0];
            $e=0;
            $ret        = array('<?xml version="1.0" encoding="ISO-8859-1"?>', '<articles>');
            $ret[]      = "<group>{$groupname}</group>";
            foreach ($result as $article)
            { 
                $name=$article->id;
                $value=$article->subject;   
                $e++;
	        $ret[] = sprintf("<article><id>%s</id><subject><![CDATA[%s]]></subject></article>", $name, $value);  
            }
	    $ret[] = "</articles>"; 

	    file_put_contents ($destfile, implode("\n", $ret));
 
            $xml = simplexml_load_file($this->DataURI);
            $existing = $xml->xpath("//bookmark[Path='{$groupname}.{$index}.xml']");
            if (sizeof ($existing) > 0) {
                $this->Remove($groupname, $index);
                return;
            }
            $bookmark = $xml->addChild('bookmark');
            $bookmark->addChild('Name', "{$first->subject}");
            $bookmark->addChild('Group', "{$groupname}");
            $bookmark->addChild('Count', "{$e}");
            $bookmark->addChild('Path', $destName);
            $bookmark->addChild('Id', "{$first->id}"); 
            file_put_contents ($this->DataURI, $xml->asXML());

            return true;
        }   
        return NULL;
    }

    function Find($group, $id)
    {
        foreach ($this->Bookmarks as $bookmark)  
            if ($bookmark->Group==$group && $bookmark->Id==$id)
                return $bookmark;
    }



    function LoadBookmarks()
    {
        $out = array('<bookmarks>');
        $DATA_URI  = DATA_PATH . "/bookmark";
        $this->bookmarks = array();
        $bookmarks = scandir ($DATA_URI);
        foreach ($bookmarks as $bookmark) {
            if (!($bookmark=='.'||$bookmark=='..')) {
                $b = new Default_Model_Bookmark("{$this->DataURI}/{$bookmark}");
                $b->Path = $bookmark;
                $out[] = $b->Serialize();
                $this->Bookmarks[] = $b;
            }
        } 
        $out[] = '</bookmarks>'; 
        file_put_contents($this->DataURI, implode("\n", $out));
    }



}

